﻿// //   Copyright 2007-2011 Comdiv (F. Sadykov) - http://code.google.com/u/fagim.sadykov/
// //   Supported by Media Technology LTD 
// //    
// //   Licensed under the Apache License, Version 2.0 (the "License");
// //   you may not use this file except in compliance with the License.
// //   You may obtain a copy of the License at
// //    
// //        http://www.apache.org/licenses/LICENSE-2.0
// //    
// //   Unless required by applicable law or agreed to in writing, software
// //   distributed under the License is distributed on an "AS IS" BASIS,
// //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// //   See the License for the specific language governing permissions and
// //   limitations under the License.
// //   
// //   MODIFICATIONS HAVE BEEN MADE TO THIS FILE

using System.Security.Principal;

namespace Comdiv.QWeb.Security {
	/// <summary>
	/// Base role resolver implementation. 
	/// 1) For roles DEFAULT and GUEST it ALWAYS return TRUE
	/// 2) For local accounts (treat that URL host is LOCALHOST) it returns TRUE (locals are admins policy)
	/// 3) For all other principals it returns NATIVE IsInRole
	/// </summary>
	internal class simpleRoleResolver : IRoleResolver {
		#region IRoleResolver Members

		public bool IsInRole(IPrincipal principal, string role, bool exact, QWebContext context = null) {
			lock (this) {
				context = context ?? QWebContext.Current;
				if (role == "DEFAULT" || role == "GUEST" || string.IsNullOrWhiteSpace(role)) return true;
				if (!principal.Identity.IsAuthenticated) return false;
				if (principal.Identity.Name == "admin") return true;
				if (context.NativeASPContext == null && context.Uri.Host == "localhost")
					return true; //called in embeded mode - no role checking needed by default if specially local url used
				if (context.NativeASPContext != null
				    &&
				    (
				    	context.NativeASPContext.Request.UserHostAddress == "127.0.0.1" ||
				    	context.NativeASPContext.Request.UserHostAddress == "::1"
				    )
				    &&
				    (
				    	principal.Identity.Name.ToLower() == WindowsIdentity.GetCurrent().Name.ToLower()
				    )
					)
					return true; // by default all local requests treats as ADMINISTRATOR's while user name is same as process account
				return principal.IsInRole(role);
			}
		}

		#endregion
	}
}